﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Data;
using System.Collections.Specialized;

namespace WebPresentation
{
    public partial class Document : System.Web.UI.Page
    {
        DocumentBO docBO = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["UserID"] == null)
                {
                    Response.Redirect("LoginPage.aspx");
                }
                if ((string)Session["Role"] != ("Admin"))
                {
                    Response.Redirect("DocumentUser.aspx");
                }
            }
        }

        protected void ImageButtonadd_Click(object sender, ImageClickEventArgs e)
        {
            if (docBO == null)
                docBO = new DocumentBO();
            string dayDir = "";
            string relativePath = "";
            if (fileUpload.PostedFile != null)
            {
                string root = Server.MapPath("") + "\\Uploads";
                string relativeRoot = "Uploads";
                if (!System.IO.Directory.Exists(root))
                {
                    System.IO.Directory.CreateDirectory(root);
                }

                string yearDir = System.IO.Path.Combine(root, Convert.ToString(DateTime.Now.Year));
                relativePath = relativeRoot + "/" + Convert.ToString(DateTime.Now.Year);
                if (!System.IO.Directory.Exists(yearDir))
                {
                    System.IO.Directory.CreateDirectory(yearDir);
                }

                string monthDir = System.IO.Path.Combine(yearDir, Convert.ToString(DateTime.Now.Month));
                relativePath = relativePath + "/" + Convert.ToString(DateTime.Now.Month);
                if (!System.IO.Directory.Exists(monthDir))
                {
                    System.IO.Directory.CreateDirectory(monthDir);
                }

                dayDir = System.IO.Path.Combine(monthDir, Convert.ToString(DateTime.Now.Day));
                relativePath = relativePath + "/" + Convert.ToString(DateTime.Now.Day);
                if (!System.IO.Directory.Exists(dayDir))
                {
                    System.IO.Directory.CreateDirectory(dayDir);
                }

                //fileUpload.PostedFile.SaveAs(dayDir);
                fileUpload.SaveAs(dayDir + "\\" + fileUpload.FileName);
            }

            int loop1, loop2;
            NameValueCollection coll;
            string strDomain = "";

            // Get names of all keys into a string array. 
            coll = Request.ServerVariables;
            String[] arr1 = coll.AllKeys;
            for (loop1 = 0; loop1 < arr1.Length; loop1++)
            {
                if (arr1[loop1].CompareTo("HTTP_ORIGIN") == 0)
                {
                    String[] arr2 = coll.GetValues(arr1[loop1]);
                    for (loop2 = 0; loop2 < arr2.Length; loop2++)
                    {
                        strDomain = Server.HtmlEncode(arr2[loop2]);
                    }
                }
            }
            relativePath = strDomain+"/"+relativePath+"/"+fileUpload.FileName;

            int docNum = Int32.Parse(txtdocno.Text);
            int dtID = Int32.Parse(ddldoctype.SelectedValue);
            int adopterID = Convert.ToInt32(Session["UserID"]);
            DateTime receiveDate = Convert.ToDateTime(txtdate.Text);
            //DateTime recDate=Convert.ToDateTime(
            string shortenedDetails = txtdetails.Text;
            int senderID = Int32.Parse(ddlsender.SelectedValue);

            if (docBO.AddNewDocument(docNum, dtID, senderID, receiveDate, adopterID, false, shortenedDetails, relativePath) > 0)
            {
                DocumentObjectSource = new ObjectDataSource();
                dtgdoc.DataBind();
                string docID = dtgdoc.Rows[dtgdoc.Rows.Count - 1].Cells[1].Text;
                Label10.Text = "Add successfully.";
                Response.Redirect("~/Recipients.aspx?docID=" + docID);
            }
            else
            {
                Label10.Text = "Add failed!";
            }

        }

        protected void ImageButtonedit_Click(object sender, ImageClickEventArgs e)
        {

            if (dtgdoc.SelectedIndex != -1)
            {
                int docID = Int32.Parse(dtgdoc.SelectedRow.Cells[1].Text);
                int docNumber = Int32.Parse(txtDocNoEdit.Text);
                int dtID = Int32.Parse(DropDownType.SelectedValue);
                int docSender = Int32.Parse(DropDownSender.SelectedValue);
                DateTime dateOfReceipt = Convert.ToDateTime(txtDateEdit.Text);
                string shortenedDetail = txtShortenedDetail.Text;
                string storePath = dtgdoc.SelectedRow.Cells[4].Text;


                if (new DocumentBO().Update(docNumber, dtID, docSender, dateOfReceipt, shortenedDetail, storePath, false, docID) > 0)
                {
                    
                    Label10.Text = "Update successfully.";
                    dtgdoc.SelectedIndex = -1;
                    dtgdoc.DataBind();
                }
                else
                {
                    Label10.Text = "Update failed!";
                }
                
            }
        }

        protected void dtgdoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            DocumentBO docBO = new DocumentBO();
            DataTable dt = (DataTable)docBO.GetByID(Int32.Parse(dtgdoc.SelectedRow.Cells[1].Text));
            txtDocNoEdit.Text = dt.Rows[0]["docNumber"].ToString();
            txtShortenedDetail.Text = dt.Rows[0]["shortenedDetail"].ToString();
            txtDateEdit.Text = dt.Rows[0]["dateOfReceipt"].ToString();
        }

        //protected void ImageButtonDel_Click(object sender, ImageClickEventArgs e)
        //{
        //    if (dtgdoc.SelectedRow != null)
        //    {
        //        if (docBO == null)
        //            docBO = new DocumentBO();
        //        int docID = Int32.Parse(dtgdoc.SelectedRow.Cells[1].Text);
        //        docBO.Delete(docID);
        //        DocumentObjectSource = new ObjectDataSource();
        //        dtgdoc.DataBind();
        //    }
        //    else
        //    {
        //        Label10.Text = "Error: No row was selected!";
        //    }
        //}

        protected void LinkButtonedit_Click(object sender, EventArgs e)
        {
            if (dtgdoc.SelectedIndex != -1)
            {
                docBO = new DocumentBO();
                DataTable dt = (DataTable)docBO.GetByID(Int32.Parse(dtgdoc.SelectedRow.Cells[1].Text));
                txtDocNoEdit.Text = dt.Rows[0]["docNumber"].ToString();
                txtShortenedDetail.Text = dt.Rows[0]["shortenedDetail"].ToString();
                txtDateEdit.Text = dt.Rows[0]["dateOfReceipt"].ToString();

            }
            else
            {
                
            }
        }

        protected void LinkButtondel_Click(object sender, EventArgs e)
        {
            if (dtgdoc.SelectedIndex != -1)
            {
                docBO = new DocumentBO();
                if (docBO.Delete(Int32.Parse(dtgdoc.SelectedRow.Cells[1].Text)) > 0)
                {
                    Label10.Text = "Delete successfully.";
                    dtgdoc.SelectedIndex = -1;
                    dtgdoc.DataBind();
                }
                else
                {
                    Label10.Text = "Delete failed!";
                }
            }
            else
            {
                
            }
        }

        protected void ImageButtonadvSearch_Click(object sender, ImageClickEventArgs e)
        {
            if (cbDocCode.Checked)
                Response.Redirect("~/Search.aspx?docCode=" + txtsearchcode.Text);
            if (cbSender.Checked)
                Response.Redirect("~/Search.aspx?sender=" + DropDownSearchSender.SelectedValue);
            if (cbReceiver.Checked)
                Response.Redirect("~/Search.aspx?receiver=" + DropDownReceiverSearch.SelectedValue);
            if (cbFromDate.Checked)
                Response.Redirect("~/Search.aspx?fromDate=" + txtdate1.Text + "&toDate=" + txtdate2.Text);
            if (cbApproved.Checked)
                Response.Redirect("~/Search.aspx?status=" + rdbApproved.Checked);
            if (cbDocType.Checked)
                Response.Redirect("~/Search.aspx?docType=" + ddltype.SelectedValue);
            
        }

        protected void LinkButtonApprove_Click(object sender, EventArgs e)
        {
            //if (Session["UserDepartment"] != "CNK")
            //{
            //    Page.ClientScript.RegisterStartupScript(this.GetType(),"PopupScript", "<script> alert('You do not have permission to approve documents!);</script>");           
            //    return;
            //}
            Response.Redirect("~/Approve.aspx");
        }
    }
}